package com.kaowen.spider;

import java.awt.geom.GeneralPath;
import java.sql.Connection;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;

import com.google.gson.Gson;
import com.kaowen.spider.util.DBManager;

/**
 * 网络爬虫 抓取商铺图片信息
 * 
 * @author thinkpad
 */
public class SpiderForBaiduImg {

	private static Logger logger = Logger.getLogger(SpiderForBaiduImg.class);
	private Connection conn = null;
	private Gson gson = null;
	QueryRunner queryRunner = null;
	GeneralPath miyunArea = null;

	public SpiderForBaiduImg() {
		try {
			conn = DBManager.getConnection();
			gson = new Gson();
			queryRunner = new QueryRunner();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void start(){
		String queryItemSql = "select t.id from sf_seller_baidu t where t.img_url <> '-1'";
		String url = "http://map.baidu.com/detail?qt=ninf&uid=0a479e4aec890f9ed23ce355";
		String updateSql = "update sf_seller_baidu t set t.img_url = ? where t.id = ?";
		try {
			List<Object[]> rsList = queryRunner.query(conn, queryItemSql, new ArrayListHandler());
			logger.info("查询出" + rsList.size() + "条结果");
			int size = rsList.size();
			for(int i=0;i<size;i++){
				String rsV = "null";
				String id = null;
				try{
					id = (String)rsList.get(i)[0];
					String rsStr = Jsoup.connect(url).ignoreContentType(true).data("uid",id).execute().body();
					Map<String, Object> map = gson.fromJson(rsStr, Map.class);
					Map content = (Map)map.get("content");
					if(content != null){
						Map ext = (Map)content.get("ext"); 
						if(ext != null){
							Map detail_info = (Map)ext.get("detail_info"); 
							if(detail_info != null){
								String image_url = (String) detail_info.get("image");
								if(image_url != null){
									if(image_url !=null){
										rsV = image_url;
									}else{
										rsV = "error:no_imageId";
									}
									
								}else{
									rsV = "error:no_image";
								}
							}else{
								rsV = "error:no_detail_info";
							}
						}else{
							rsV = "error:no_ext";
						}
						
					}else{
						rsV = "error:no_content";
					}
					
				}catch(Exception e){
					logger.info("抓取" + id + "出现错误，错误信息为："+e.getMessage());
				}finally{
					queryRunner.update(conn, updateSql,rsV,id);
					logger.info(i+"/" + size + "\tID:" + id + "\t结果："+rsV);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		SpiderForBaiduImg spider = new SpiderForBaiduImg();
		spider.start();
	}
}
